const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const { v4: uuidv4 } = require('uuid');
const fs = require('fs');

const app = express();
const port = 3000;

// 中间件配置
app.use(cors());
app.use(bodyParser.json());

// 内存存储（生产环境建议使用数据库）
let anchorsStorage = {};

// 创建空间锚点
app.post('/anchors', (req, res) => {
    const anchorData = req.body;
    console.log(anchorData)
    // 生成唯一ID
    const anchorId = uuidv4();
    
    // 创建记录
    const newAnchor = {
        id: anchorId,
        ...anchorData,
        createdAt: new Date().toISOString()
    };

    anchorsStorage[anchorId] = newAnchor;
    saveToFile();
    res.status(201).json(newAnchor);
});

// 获取所有锚点
app.get('/anchors', (req, res) => {
    loadFromFile();
    res.json(Object.values(anchorsStorage));
});

// 获取单个锚点
app.get('/anchors/:id', (req, res) => {
    const anchor = anchorsStorage[req.params.id];
    anchor ? res.json(anchor) : res.status(404).send('Anchor not found');
});

// 更新锚点
app.put('/anchors/:id', (req, res) => {
    const anchorId = req.params.id;
    if (!anchorsStorage[anchorId]) {
        return res.status(404).send('Anchor not found');
    }

    anchorsStorage[anchorId] = {
        ...anchorsStorage[anchorId],
        ...req.body,
        updatedAt: new Date().toISOString()
    };

    res.json(anchorsStorage[anchorId]);
});

// 删除锚点
app.delete('/anchors/:id', (req, res) => {
    const anchorId = req.params.id;
    if (!anchorsStorage[anchorId]) {
        return res.status(404).send('Anchor not found');
    }

    delete anchorsStorage[anchorId];
    res.status(204).send();
});

// 启动服务器
app.listen(port, () => {
    console.log(`Server running on http://localhost:${port}`);
});

// 保存到文件
function saveToFile() {
    fs.writeFileSync('./anchors.json', JSON.stringify(anchorsStorage));
}

// 从文件加载
function loadFromFile() {
    try {
        anchorsStorage = JSON.parse(fs.readFileSync('anchors.json'));
    } catch (error) {
        anchorsStorage = {};
    }
}